﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;

namespace Behavior.Rotate
{
    public class RotateThumb : Thumb
    {
        private double _initialAngle;
        private Control _item;
        private Canvas _canvas;
        private Vector _initialVector;
        private Point _centerPoint;

        public RotateThumb()
        {
            DragStarted += OnDragStarted;
            DragDelta += OnDragDelta;
        }

        private void OnDragDelta(object sender, DragDeltaEventArgs e)
        {
            if (_item == null || _canvas == null) return;

            Point currentPoint = Mouse.GetPosition(_canvas);
            Vector deltaVector = Point.Subtract(currentPoint, _centerPoint);
            double angle = Vector.AngleBetween(_initialVector, deltaVector);
            RotateTransform rotateTransform = _item.RenderTransform as RotateTransform;
            rotateTransform.Angle = _initialAngle + Math.Round(angle, 0);
            _item.InvalidateMeasure();
        }

        private void OnDragStarted(object sender, DragStartedEventArgs e)
        {
            _item = DataContext as Control;
            if (_item == null) return;
            _canvas = VisualTreeHelper.GetParent(_item) as Canvas;
            if (_canvas == null) return;

            RotateTransform rotateTransform = _item.RenderTransform as RotateTransform;
            if (rotateTransform == null)
            {
                _item.RenderTransform = new RotateTransform(0);
                _initialAngle = 0;
            }
            else
            {
                _initialAngle = rotateTransform.Angle;
            }
            Point initialPoint = Mouse.GetPosition(_canvas);
            _centerPoint = _item.TranslatePoint(new Point(_item.Width * _item.RenderTransformOrigin.X, _item.Height * _item.RenderTransformOrigin.Y), _canvas);
            _initialVector = Point.Subtract(initialPoint, _centerPoint);
        }
    }
}
